package de.uni.muenster.idw2.threads;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.Display;
import android.view.View;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import de.uni.muenster.idw2.BuildingInformation;
import de.uni.muenster.idw2.adapter.BuildingGalleryAdapter;
import de.uni.muenster.idw2.interfaces.AdapterLoaderInterface;

public class GridLoaderThread extends AsyncTask<Void, Void, Void> implements AdapterLoaderInterface{
	
	private LinkedList<Drawable> drawables;
	private BuildingInformation act;
	private ProgressBar progressBar;
	private BuildingGalleryAdapter adapter;
	private ArrayList<String> paths;
	private final Gallery gridView;
	private final ImageView imageView;
	
	private Drawable startIcon = null;

	public GridLoaderThread(BuildingInformation act, ProgressBar progressBar, BuildingGalleryAdapter adapter, LinkedList<Drawable> drawables, ArrayList<String> paths, Gallery gridView, ImageView imageView){
		this.act = act;
		this.progressBar = progressBar;
		this.adapter = adapter;
		this.drawables = drawables;
		this.paths = paths;
		this.gridView = gridView;
		this.imageView = imageView;
		
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressBar.setVisibility(View.VISIBLE);
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		
		ExecutorService executorService = Executors.newFixedThreadPool(6);
		for (int i = 0; i < paths.size(); i++) {
			
			Runnable worker = new SilngelImgThread(this, paths.get(i), i);
			executorService.execute(worker);
		}
		
		executorService.shutdown();
		
		while (!executorService.isTerminated()) {
			
		}
		
		return null;
	}

	
	@Override
	protected void onProgressUpdate(Void... values) {
		adapter.serImageList(drawables);
		long pos = gridView.getSelectedItemId();
		gridView.setAdapter(adapter);
		gridView.setSelection((int)pos);
		
		if(startIcon != null){
			imageView.setImageDrawable(startIcon);
		}
	}
	
	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		progressBar.setVisibility(View.GONE);
	}
	
	public synchronized void addImage(Drawable drawable,int i){
		
		if(i != 0 && drawable != null){
			drawables.add(drawable);
		}
		else if(drawable != null){
			startIcon = drawable;
		}
		else{
			adapter.removeOneObject();
		}
		publishProgress();
	}

}
